package userService

import (
	"crypto/md5"
	"encoding/hex"
	"errors"
	userDto "news_for_deepseek_interface/dto/admin/system/user"
	"news_for_deepseek_interface/model"
	adminModel "news_for_deepseek_interface/model/admin"
)

func Update(params userDto.UpdateRequest) error {
	db := model.GetInstance().GetDB()

	// 检查用户是否存在
	var user adminModel.AdminStruct
	if err := db.First(&user, params.Id).Error; err != nil {
		return err
	}

	// 如果修改了用户名，检查新用户名是否已存在
	if user.Username != params.Username {
		var count int64
		if err := db.Model(&adminModel.AdminStruct{}).
			Where("username = ? AND id != ?", params.Username, params.Id).
			Count(&count).Error; err != nil {
			return err
		}
		if count > 0 {
			return errors.New("当前用户名已存在")
		}
	}

	if user.Mobile != params.Mobile {
		var count2 int64
		if err := db.Model(&adminModel.AdminStruct{}).
			Where("mobile = ? AND id != ?", params.Mobile, params.Id).
			Count(&count2).Error; err != nil {
			return err
		}
		if count2 > 0 {
			return errors.New("当前手机号已存在")
		}
	}

	// 准备更新数据
	updates := map[string]interface{}{
		"username": params.Username,
		"status":   params.Status,
		"mobile":   params.Mobile,
		"expires":  params.Expires,
		"province": params.Region[0],
		"city":     params.Region[1],
		"area":     params.Region[2],
		"address":  params.Address,
	}

	// 如果提供了新密码，更新密码
	if params.Password != "" {
		data := []byte(params.Password + "|" + user.Salt)
		hash := md5.Sum(data)
		updates["password"] = hex.EncodeToString(hash[:])
	}

	return db.Model(&user).Updates(updates).Error
}
